import FactorAPI from '@/api/Factor';
import {
  clearDictByCodes,
  ClickModal,
  FieldCols,
  mapField,
  useCall,
  useFormValue,
  useReq,
  useToggle,
} from '@/components';
import { forkHandler } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, Divider, Form, Input, message, Space } from 'antd';
import React, { useEffect } from 'react';

const FIELDS = [
  ['id', '', 'hidden', { noStyle: true, colProps: { xs: 0, md: 0, xl: 0 } }],
  ['factorObject', '因子对象', 'dict', { required: true, code: 'factorObject' }],
  [
    'code',
    '因子代码',
    null,
    {
      required: true,
      getFieldProps(e, i, form) {
        return { readOnly: useFormValue(form, 'id', Boolean) };
      },
    },
  ],
  ['cname', '因子名称', null, { required: true }],
  [
    'javaType',
    '数据类型',
    'select',
    {
      required: true,
      options: ['BigDecimal', 'Double', 'Integer', 'String'].map((value) => ({ value })),
    },
  ],
  [
    'factorDesc',
    '因子说明',
    'textarea',
    {
      colProps: { xs: 24, md: 24, xl: 24 },
      itemProps: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
    },
  ],
].map(mapField);

const col = { xs: 12 };

function InsertFactorObject() {
  const [form] = Form.useForm();
  const [visi, toggle] = useToggle();
  const xhr = useReq(FactorAPI.addFactorObject);

  const handleSubmit = useCall(async () => {
    const { code, cnName } = await form.validateFields().catch(catchAndScrollFor(form));
    try {
      await xhr.start(code, cnName);
      toggle();
      clearDictByCodes('factorObject');
    } catch (error) {
      message.error(error.msg || error.message);
    }
  });

  useEffect(() => {
    if (visi) form.resetFields();
  }, [visi]);

  if (visi) {
    return (
      <Form layout='inline' form={form} onFinish={handleSubmit}>
        <Form.Item name='code' rules={[{ required: true, message: '请输入因子对象编码' }]}>
          <Input placeholder='请输入因子对象编码' />
        </Form.Item>
        <Form.Item name='cnName' rules={[{ required: true, message: '请输入因子对象名称' }]}>
          <Input placeholder='请输入因子对象名称' />
        </Form.Item>
        <Space size='small'>
          <Button type='primary' htmlType='submit' loading={xhr.status === 'loading'}>
            确认添加
          </Button>
          <Button disabled={xhr.status === 'loading'} onClick={toggle}>
            取消
          </Button>
        </Space>
      </Form>
    );
  }

  return (
    <Button type='primary' onClick={toggle}>
      + 新增因子对象
    </Button>
  );
}

function FactorEditModal({ onOk, onToggle, item, ...rest }) {
  const [form] = Form.useForm();

  const content = (
    <>
      <InsertFactorObject />
      <Divider />
      <Form form={form}>
        <FieldCols form={form} colProps={col} fields={FIELDS} />
      </Form>
    </>
  );

  const handleOk = useCall(async () => {
    const values = await form.validateFields().catch(catchAndScrollFor(form));
    return onOk?.(values);
  });

  const handleToggle = useCall(
    forkHandler((visi) => {
      if (visi) item ? form.setFieldsValue(item) : form.resetFields();
    }, onToggle),
  );

  return <ClickModal {...rest} content={content} onOk={handleOk} onToggle={handleToggle} />;
}

export default FactorEditModal;
